package com.cloud.rou.im.client.msg;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类说明：存放到队列的元素
 */
public class AckDelay<T> implements Delayed {
    /**
     * 到期时间，单位毫秒
     */
    private long expire;
    private T data;
    private final AtomicInteger retryTime ;


    public AckDelay(T data, long expire,int retryTime) {
        this.data = data;
        this.expire = TimeUnit.NANOSECONDS.convert(expire,
                TimeUnit.MILLISECONDS) + System.nanoTime();
        this.retryTime = new AtomicInteger(retryTime);
    }

    public Integer getRetryTime(){
        return retryTime.get();
    }

    public Integer decrementAndGet(){
        return retryTime.decrementAndGet();
    }

    public void setExpire(long expire) {
        this.expire = TimeUnit.NANOSECONDS.convert(expire,
                TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    public long getExpire() {
        return expire;
    }

    public T getData() {
        return data;
    }

    @Override
    public int compareTo(Delayed o) {
        long d = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return (d == 0) ? 0 : ((d > 0) ? 1 : -1);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long d = unit.convert(this.expire - System.nanoTime(),
                TimeUnit.NANOSECONDS);
        return d;
    }


}
